package com.ruoyi.flowable.rpc;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.web.domain.BaseEntity;
import com.ruoyi.system.api.domain.SysRole;
import com.ruoyi.system.api.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class RemoteSystemService {

    @Autowired
    private IRemoteSystemService remoteSystemService;

    private <T> List<T> resultToList(R<List<T>> dataResult) {
        if (R.FAIL == dataResult.getCode()) {
            throw new ServiceException(dataResult.getMsg());
        }
        return dataResult.getData();
    }

    private <T> T resultToBean(R<T> dataResult) {
        if (R.FAIL == dataResult.getCode()) {
            throw new ServiceException(dataResult.getMsg());
        }
        return dataResult.getData();
    }

    public List<SysUser> getUsers(SysUser sysUser) {
        //远程调用system接口获取所有电站信息
        R<List<SysUser>> dataResult = remoteSystemService.getUsers(beanToMap(sysUser), SecurityConstants.INNER);
        return resultToList(dataResult);
    }

    public List<SysRole> getRoles(SysRole sysRole) {
        //远程调用system接口获取所有电站信息
        R<List<SysRole>> dataResult = remoteSystemService.getRoles(beanToMap(sysRole), SecurityConstants.INNER);
        return resultToList(dataResult);
    }

    private Map<String, Object> beanToMap(Object obj) {
        Map<String, Object> paraMap = BeanUtil.beanToMap(obj, false, true);
        if (obj instanceof BaseEntity) {
            paraMap.remove("params");
        }
        return paraMap;
    }

    public SysUser getUserById(Long userId) {
        //远程调用system接口获取所有电站信息
        R<SysUser> dataResult = remoteSystemService.getUserById(userId, SecurityConstants.INNER);
        return resultToBean(dataResult);
    }

    public SysRole getRoleById(Long roleId) {
        //远程调用system接口获取所有电站信息
        R<SysRole> dataResult = remoteSystemService.getRoleById(roleId, SecurityConstants.INNER);
        return resultToBean(dataResult);
    }

}
